<?php

namespace app\company\controller;

use app\company\validate\DeliverDriverValidate;
use app\service\traits\Crud;
use app\company\model\DeliverDriver as DeliverDriverModel;
use Exception;
use think\facade\Request;
use think\Response;

class DeliverDriver extends Base
{
    private DeliverDriverModel $model;

    use Crud;

    public function initialize()
    {
        parent::initialize();
        $this->model            = new DeliverDriverModel();
        $this->validateClass    = DeliverDriverValidate::class;
        $this->withSearch       = 'id,no,name';
        $this->isGs             = true;
        $this->append           = 'sex_text';
        $this->checkUniqueField = ['no', 'user_name'];
    }


    /**
     * 账户列表
     * @return Response
     */
    public function amount(): Response
    {
        $param = request()->param();
        validate($this->validateClass)->scene('list')->check($param);
        $sql   = $this->model;
        $sql   = $sql->Gs()->withSearch($this->withSearch, $param);
        $sql   = $sql->field("id,name,money");
        $count = $sql->count();
        if (Request::param('is_export', 0) != 1) $sql = $sql->page($param['page'], $param['limit']);
        $list = $sql->order($this->orderSort)->select()->each(function ($item) {
            $item->money_all      = $item->deliverDriverAccountLogs()->where('type', 1)->sum('amount');//总金额
            $item->money_withdraw = $item->deliverDriverAccountLogs()->where('type', 2)->sum('amount');//提现金额
        });
        if (Request::param('is_export', 0) == 1) $list = $sql->select();
        return $this->success('获取成功', compact('count', 'list'));
    }


    /**
     * 提现
     * @return Response
     */
    public function withdraw(): Response
    {
        $param = request()->param();
        validate($this->validateClass)->scene('withdraw')->check($param);
        $this->model->startTrans();
        try {
            if($param['money'] <= 0) exception('提现金额必须大于0');
            //扣减余额
            if (!$info = $this->model->where('id', $param['deliver_driver_id'])->find()) exception('参数错误');
            $money = $info->money;
            if ($money < $param['money']) exception('余额不足');
            $info->inc('money', $param['money'] * -1)->update();
            //添加提现记录
            $no = 'TX' . date("Ymd") . rand(10000, 99999);
            $this->model->deliverDriverWithdraws()->save([
                'deliver_driver_id' => $info->id,
                'company_id'        => $info->company_id,
                'no'                => $no,
                'amount'            => $param['money'],
                'type'              => 2,
                'remark'            => request()->param('remark', '')
            ]);

            //添加提现日志
            $this->model->deliverDriverAccountLogs()->save([
                    'deliver_driver_id' => $info->id,
                    'company_id'        => $info->company_id,
                    'withdraw_no'       => $no,
                    'type'              => 2,
                    'amount'            => $param['money'],
                    'money'             => $money]
            );
            $this->model->commit();
            return $this->success('提现成功');
        } catch (Exception $e) {
            $this->model->rollback();
            return $this->error($e->getMessage());
        }
    }

}